package com.itheima.service.impl;

import com.itheima.dao.CarItemDao;
import com.itheima.dao.ProductDao;
import com.itheima.domain.CarItem;
import com.itheima.domain.Product;
import com.itheima.service.CarItemService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

@Service
public class CarItemServiceImpl implements CarItemService {
    @Autowired
    private CarItemDao carItemDao;
    @Autowired
    private ProductDao productDao;


    @Override
    public int insertCarItem(int userId, int productId) {
        CarItem carItemIsExit = carItemDao.selectIsExit(userId, productId);
        if (carItemIsExit != null) {
            return -1;//已存在购物车项目
        }
        Product product = productDao.selectByProductId(productId);
        if (product != null) {
            CarItem carItem = new CarItem();
            carItem.setUserId(userId);
            ;
            carItem.setProductId(productId);
            carItem.setSellerId(product.getUserId());
            carItem.setStatus(0);
            carItem.setCreateTime(new Date());
            int result = carItemDao.addCarItem(carItem);
            if (result > 0) {
                return 1;
            }
        }
        return 0;
    }

    @Override
    public CarItem findCarItemByUserIdAndProductId(int userId, int productId) {
        return carItemDao.selectIsExit(userId, productId);
    }

    @Override
    public List<CarItem> findCarItemsByUserId(int userId) {
        return carItemDao.selectCarItemsByUserId(userId);
    }

    @Override
    public int deleteCarItem(int id) {
        return carItemDao.deleteCarItem(id);
    }

    @Override
    public int updateCarItemStatus(Integer carItemId, Integer status) {
        return carItemDao.updateCarItemStatus(carItemId, status);
    }
}
